import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:starfish_tenement_app/component/app_bar/app_search_bar.dart';
import 'package:starfish_tenement_app/component/banner/home_banner_widget.dart';
import 'package:starfish_tenement_app/pages/home/home_vm.dart';
import 'package:starfish_tenement_app/pages/house_resource/detail/house_resource_detail_page.dart';
import 'package:starfish_tenement_app/route/route_utils.dart';
import 'package:starfish_tenement_app/styles/app_colors.dart';

import '../../api/models/better_choice_data.dart';
import '../../api/models/home_banner_data.dart';
import '../../api/models/house_res_data.dart';
import '../../component/filter/filter_menu_widget.dart';
import '../../component/house_list/house_res_list_item.dart';
import '../../component/icon_text/icon_text.dart';
import '../../component/scan/scan_page.dart';
import '../../component/sliver/sliver_header.dart';
import '../../component/title/app_text.dart';
import '../../component/title/big_title.dart';
import '../apartment/apartment_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  final HomeViewModel _viewModel = HomeViewModel();
  var _first = true;
  var _firstCheck = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    // 首次加载数据
    _viewModel.onLoad();
  }

  /// 每当应用程序的生命周期状态发生变化时，就会触发此事件
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      if (!_first) {
        if (_firstCheck) {
          changeLocation();
        }
        _firstCheck = false;
      }
      _first = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return _viewModel;
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
            child: RefreshIndicator(
          onRefresh: _viewModel.handleRefresh,
          child: Padding(
            padding: EdgeInsets.only(left: 16.w, right: 15.w),
            child: CustomScrollView(
              slivers: [
                SliverToBoxAdapter(
                  child: Column(
                    children: [
                      // 位置、搜索栏、扫码
                      _titleBar(),
                      // banner轮播
                      _banner(),
                      //金刚位按钮
                      _jinGangView(),
                      //本期优选
                      BigTitle(bigTitle: "本期优选"),
                      _betterChoice(),
                      // 周边推荐
                      BigTitle(
                          bigTitle: "周边推荐", showRight: true, onRightTap: () {}),
                      //地图缩略图
                      _mapView(),
                    ],
                  ),
                ),

                //吸顶布局
                SliverHeader(
                  children: [
                    // 精选好房
                    BigTitle(bigTitle: "精选好房"),
                    //筛选条件区域
                    _filterArea()
                  ],
                ),

                //房源列表
                _houseResListView(),
              ],
            ),
          ),
        )),
      ),
    );
  }

  ///获取定位
  Future changeLocation() async {
    _viewModel.changeLocation("北京");
    // AppPermission.requestAppPermission(context, (status) {
    //   if (status) {
    //     //开启定位
    //     Location.initLocationSDK().then((value) {
    //       _homeVM.setShowMap();
    //       Location.startLocationOnce((json) {
    //         var city = json['e'];
    //         _homeVM.changeLocation(city);
    //       });
    //     });
    //   }
    // });
  }

  ///顶部标题搜索栏
  Widget _titleBar() {
    return Container(
      padding: EdgeInsets.only(top: 18.h),
      width: double.infinity,
      child: Row(
        children: [
          // 当前位置
          GestureDetector(
            onTap: () {
              // 点击切换当前位置
              changeLocation();
            },
            child: Row(
              children: [
                Consumer<HomeViewModel>(builder: (context, vm, child) {
                  return Text(
                    vm.currentCity,
                    style: TextStyle(
                        fontSize: 14.sp, color: AppColors.textColor5a),
                  );
                }),
                4.horizontalSpace,
                Image.asset(
                  "assets/images/icon_daosanjiao.png",
                  width: 9.w,
                  height: 5.h,
                )
              ],
            ),
          ),

          // 搜索栏
          Expanded(
              child: AppSearchBar(
                  searchType: SearchType.square,
                  hintText: "公司/地铁/小区，马上搜",
                  // 右侧扫码按钮
                  showRightMenu: true,
                  rightMenu: GestureDetector(
                    child: Image.asset("assets/images/icon_scan.png",
                        width: 19.r, height: 19.r),
                    onTap: () {
                      // 打开扫码
                      RouteUtils.push(context, ScanPage(
                        scanCallback: (code) {
                          showToast(code ?? "");
                        },
                      ));
                    },
                  ))),
        ],
      ),
    );
  }

  ///banner轮播
  Widget _banner() {
    return Container(
      padding: EdgeInsets.only(top: 22.h, bottom: 22.h),
      child: Selector<HomeViewModel, List<HomeBannerData>?>(
          builder: (context, List<HomeBannerData>? bannerList, child) {
        return BannerWidget(
          dotType: BannerDotType.circle,
          setRadius: true,
          bannerData: _viewModel.generalBannerList(bannerList),
          bannerClick: (index) {
            // banner点击
          },
        );
      }, selector: (context, vm) {
        return vm.banner;
      }),
    );
  }

  ///金刚位
  Widget _jinGangView() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        IconText(
          text: "整租",
          iconSize: Size(30.w, 31.h),
          iconPath: "assets/images/icon_home_zhengzu.png",
          onTap: () {},
        ),
        IconText(
          text: "合租",
          iconSize: Size(30.w, 31.h),
          iconPath: "assets/images/icon_home_hezu.png",
          onTap: () {},
        ),
        IconText(
          text: "资讯",
          iconSize: Size(30.w, 31.h),
          iconPath: "assets/images/icon_home_zixun.png",
          onTap: () {},
        ),
        IconText(
          text: "新房源",
          iconSize: Size(30.w, 31.h),
          iconPath: "assets/images/icon_home_xinfangyuan.png",
          onTap: () {},
        )
      ],
    );
  }

  ///本期优选
  Widget _betterChoice() {
    return SizedBox(
        width: double.infinity,
        height: 172.h,
        child: Selector<HomeViewModel, List<BetterChoiceData>?>(
          builder: (context, List<BetterChoiceData>? choiceList, child) {
            var data0 = _viewModel.generalBetterChoiceData(0);
            var data1 = _viewModel.generalBetterChoiceData(1);
            var data2 = _viewModel.generalBetterChoiceData(2);
            return Row(children: [
              _commonBetterChoiceView(
                  height: 172.h,
                  width: 172.w,
                  imgHeight: 172.h,
                  imgWidth: 172.w,
                  imgPath: data0?.imgurl ??
                      "https://images.pexels.com/photos/2501965/pexels-photo-2501965.jpeg",
                  title: data0?.title ?? "精品装修",
                  titleSize: 17.sp,
                  subTitle: data0?.subtitle ?? "舒适的环境",
                  subTitleSize: 12.sp,
                  subTitleColor: AppColors.textColor78,
                  onTap: () {
                    RouteUtils.push(context, ApartmentPage());
                  }),
              SizedBox(width: 9.w),
              Expanded(
                  child: Column(children: [
                Expanded(
                  child: _commonBetterChoiceView(
                      height: 80.h,
                      imgHeight: 80.h,
                      imgWidth: double.infinity,
                      imgPath: data1?.imgurl ??
                          "https://images.pexels.com/photos/101808/pexels-photo-101808.jpeg",
                      title: data1?.title ?? "温馨小窝",
                      titleSize: 17.sp,
                      subTitle: data1?.subtitle ?? "惬意的生活",
                      subTitleSize: 12.sp,
                      titleColor: Colors.white,
                      subTitleColor: Colors.white,
                      textPadding: EdgeInsets.only(left: 16.w, top: 13.h),
                      titleWeight: FontWeight.w600),
                ),
                SizedBox(height: 11.w),
                Expanded(
                  child: _commonBetterChoiceView(
                      height: 80.h,
                      imgHeight: 80.h,
                      imgWidth: double.infinity,
                      imgPath: data2?.imgurl ??
                          "https://images.pexels.com/photos/1396122/pexels-photo-1396122.jpeg",
                      title: data2?.title ?? "大牌商圈",
                      titleSize: 17.sp,
                      subTitle: data2?.subtitle ?? "选择更多",
                      subTitleSize: 12.sp,
                      titleColor: Colors.white,
                      subTitleColor: Colors.white,
                      textPadding: EdgeInsets.only(left: 16.w, top: 13.h),
                      titleWeight: FontWeight.w600),
                )
              ]))
            ]);
          },
          selector: (context, vm) {
            return vm.betterChoice;
          },
        ));
  }

  ///本期优选通用布局
  Widget _commonBetterChoiceView(
      {double? height,
      double? width,
      String? imgPath,
      double? imgHeight,
      double? imgWidth,
      EdgeInsetsGeometry? textPadding,
      String? title,
      String? subTitle,
      double? titleSize,
      double? subTitleSize,
      Color? titleColor,
      Color? subTitleColor,
      FontWeight? titleWeight,
      GestureTapCallback? onTap}) {
    return GestureDetector(
        onTap: onTap,
        child: SizedBox(
          height: height,
          width: width,
          child: Stack(
            children: [
              Image.network(
                imgPath ??
                    "https://images.pexels.com/photos/2501965/pexels-photo-2501965.jpeg",
                height: imgHeight,
                width: imgWidth,
                fit: BoxFit.fill,
              ),
              Container(
                  padding:
                      textPadding ?? EdgeInsets.only(left: 14.w, top: 23.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      AppText(
                        text: title ?? "",
                        fontSize: titleSize ?? 17.sp,
                        textColor: titleColor,
                        fontWeight: titleWeight,
                      ),
                      AppText(
                        text: subTitle ?? "",
                        fontSize: subTitleSize ?? 12.sp,
                        textColor: subTitleColor ?? AppColors.textColor78,
                      )
                    ],
                  ))
            ],
          ),
        ));
  }

  ///地图缩略图
  Widget _mapView() {
    return Container(
        color: Colors.grey,
        height: 162.h,
        width: double.infinity,
        alignment: Alignment.center,
        child: Consumer<HomeViewModel>(
          builder: (context, vm, child) {
            // todo
            return Image.asset("assets/images/image_map.png",
                width: double.infinity,
                height: double.infinity,
                fit: BoxFit.fill);
            // return AMapView();
          },
        ));
  }

  ///筛选条件区域
  Widget _filterArea() {
    return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
      FilterMenuWidget(
        name: "区域",
        selected: true,
        onTap: () {
          print("_filterArea=>区域");
        },
      ),
      FilterMenuWidget(
          name: "租金",
          onTap: () {
            print("_filterArea=>租金");
          }),
      FilterMenuWidget(
          name: "户型",
          onTap: () {
            print("_filterArea=>户型");
          }),
      FilterMenuWidget(
          name: "筛选",
          onTap: () {
            print("_filterArea=>筛选");
          })
    ]);
  }

  ///房源列表
  Widget _houseResListView() {
    return Selector<HomeViewModel, List<HouseResData>?>(
        builder: (context, houseResList, child) {
      return SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
        var item = houseResList?[index];
        return HouseListItem(
          data: item,
          onTap: () {
            RouteUtils.push(context, HouseResourceDetailPage(id: item?.id));
          },
        );
      }, childCount: houseResList?.length ?? 0));
    }, selector: (context, vm) {
      return vm.houseResList;
    });
  }
}
